import React, { useCallback, useState, useRef } from 'react';
import ShoppingCartHeader from './Component/ShoppingCartHeader';
import ShoppingCartBody from './Component/ShoppingCartBody';
import { mockBodyData } from './mockdata'

import './ShoppingCart.css';

function ShoppingCart() {
    const cartList = useRef([]);
    const update = useForceUpdate();

    const addCartList = useCallback((id) => {
        let list = cartList.current;
        let findData = list.find(item => item.id === id);

        if (findData) {
            findData.num++;
        } else {
            let findDataFromMock = mockBodyData.find(item => item.id === id);
            findDataFromMock.num++;
            list.push(findDataFromMock)
        }
        update();
    }, []);

    const deleteCartList = useCallback((id) => {
        let findData = cartList.current.find(item => item.id === id);
        if (findData) {
            findData.num = 0;
        }
        cartList.current = cartList.current.filter(item => item.id != id);
        update();
    }, []);

    return <div className="wind-cart-wrap">
        <div className="wind-cart-box">
            <ShoppingCartHeader
                cartList={cartList}
                deleteCartList={deleteCartList}
            />
            <ShoppingCartBody
                goods={mockBodyData}
                addCartList={addCartList}
                cartList={cartList}
            />
        </div>
    </div>
}

function useForceUpdate() {
    let [ignore, setState] = useState(0);

    const forceUpdate = useCallback(() => {
        setState(x => x + 1);
    }, [])

    return forceUpdate;
}

export default ShoppingCart